'use client'
import React, { useState, useCallback, useEffect } from 'react'
import { useSearchParams, useRouter, usePathname } from 'next/navigation';
import BlogContext from '@/context/blogContext'
import BlogTemplate from '@/template/blogs/BlogTemplate'

export default function BlogLayout({ params, blogs }) {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();

  const pathSlug = params?.slug || (pathname.split('/').pop() || 'all');
  const [articles, setArticles] = useState([]);
  const [slug, setSlug] = useState(pathSlug);
  const [limit] = useState(12);
  const [page, _setPage] = useState();
  const [total, setTotal] = useState(0);
  const [activeTotal, setActiveTotal] = useState(0);

  const fetchArticles = useCallback(async (currSlug, currPage) => {
    if (!currSlug || !currPage) return;
    const res = await fetch(`/api/articles/${currSlug}?page=${currPage}&limit=${limit}`);
    const data = await res.json();
    setTotal(data.total);
    setActiveTotal(data.activeTotal);
    setArticles(data.articles);
  }, [limit]);

  useEffect(() => {
    const urlPage = parseInt(searchParams.get('page'), 10);
    let needReplace = false;
    const params = new URLSearchParams(searchParams);
    if (!urlPage || isNaN(urlPage) || urlPage < 1) {
      params.set('page', '1');
      _setPage(1);
      needReplace = true;
    } else if (page !== urlPage) {
      _setPage(urlPage);
    }

    if (slug !== pathSlug) {
      setSlug(pathSlug);
    }

    if (needReplace) {
      router.replace(`${pathname}?${params.toString()}`);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams, router, pathname, pathSlug]);

  useEffect(() => {
    if (slug && page) {
      fetchArticles(slug, page);
    }
  }, [slug, page, fetchArticles]);

  const setPage = useCallback((newPage) => {
    _setPage(newPage);
    const params = new URLSearchParams(searchParams);
    params.set('page', newPage.toString());
    router.push(`${pathname}?${params.toString()}`);
  }, [router, searchParams, pathname]);

  const handleChangeBlog = (blog) => {
    if (!blog) return;
    setSlug(blog.slug);
    _setPage(1);
    router.push(`/blogs/${blog.slug}?page=1`);
  }

  const contextValue = { slug, page, limit, setPage, blogs, handleChangeBlog, articles, total, activeTotal }

  return (
    <BlogContext.Provider value={contextValue}>
      <BlogTemplate template={blogs.find(b => b.slug === slug)?.template} />
    </BlogContext.Provider>
  )
}